import React, {PureComponent} from 'react';
import {
  View,
  StyleSheet,
  Text,
  TextInput,
  Image,
  TouchableOpacity,
  Keyboard,
  Modal,
  ScrollView,
} from 'react-native';
import I18n from 'react-native-i18n';
import {connect} from 'react-redux';
import BaseComponent from '../base/BaseComponent';
import {
  TextButton,
  LinearBoardButton,
  LinearButton,
} from '../../components/Button';
import {NormalHeader} from '../../components/NavigationHeader';
import {showToast} from '../../components/Toast';
import {userLogout} from '../../redux/action';
import Clipboard from '@react-native-community/clipboard';
import {queryWalltBalance} from '../../redux/action/index';
import ModalHandler from '../../components/ModalHandler';
import WalletUtils from '../../utils/wallet/WalletUtils';
import {offerPrice} from '../../api/auction';
import {LinerBoardTextInput} from '../../components/TextInput';
import ChainUtils from '../../utils/chain/ChainUtils';
import BigNumber from 'bignumber.js';
import WalletConnectModal from '../../components/WalletConnectModal';

//#FFCB26
class PriceBid extends BaseComponent {
  constructor(props) {
    super(props);

    this.state = {
      amount: 0,
      confirmValid: false,
      modalVisible: false,
      loading: false,
      password: '',
      gasUsed: 0,
      success: false,
      approveValue: 0,
      canBid: false,
      needApprove: false,
      callFunc: '',
      queryingGas: false,
      queryingCreateGas: false,
      showWalletConnect: false,
      tx: undefined,
    };
  }

  onPressBackground = () => {
    if (this.state.loading) {
      return;
    }

    this.setState({
      modalVisible: false,
      loading: false,
    });
  };

  async componentDidMount() {
    this.props.queryWalltBalance();

    let {
      payCoinAddress,
      payCoinDecimal,
    } = this.props.navigation.state.params.auction;

    console.log(payCoinAddress);

    if (payCoinAddress == '0x0000000000000000000000000000000000000000') {
      return;
    }
    this._showLoading();

    console.log('查询授权额度为');
    console.log(this.props.userInfo.metamaskAddress);
    console.log(this.props.proxy.address);
    console.log(payCoinAddress);
    console.log(payCoinDecimal);

    let approveValue = await WalletUtils.queryTokenAllowance(
      this.props.userInfo.metamaskAddress,
      this.props.proxy.address,
      payCoinAddress,
      payCoinDecimal,
    );
    console.log('授权额度为' + approveValue);

    this.setState({
      approveValue,
    });
    this._hideLoading();
  }

  _handlerView = () => {
    let {payCoin} = this.props.navigation.state.params.auction;
    let {canBid, needApprove, amount} = this.state;

    return (
      <View style={{width: '100%'}}>
        <Text
          style={{
            fontWeight: 'bold',
            marginTop: 20,
            marginBottom: 20,
            color: '#6701F4',
          }}>
          {needApprove
            ? `Approve signIn allowance ${amount} ${payCoin}.`
            : 'Send a bid transaction'}
        </Text>
        <Image
          style={{height: 1, width: '100%', marginBottom: 10}}
          source={require('../../assets/auction/line.png')}></Image>
        <View style={{width: '100%'}}>
          <View
            style={{
              flexDirection: 'row',
              justifyContent: 'space-between',
              width: '100%',
              marginTop: 0,
            }}>
            <Text style={{lineHeight: 30, color: '#6902F4'}}>
              Call Function
            </Text>
            <Text
              style={{
                fontWeight: 'bold',
                color: '#6902F4',
                lineHeight: 30,
              }}>
              {this.state.callFunc}
            </Text>
          </View>
        </View>
        <View style={{width: '100%', marginBottom: 10}}>
          <View
            style={{
              flexDirection: 'row',
              justifyContent: 'space-between',
              width: '100%',
              marginTop: 0,
            }}>
            <Text style={{lineHeight: 30, color: '#6902F4'}}>Gas Used</Text>
            <Text
              style={{
                fontWeight: 'bold',
                color: '#6902F4',
                lineHeight: 30,
              }}>
              {`${this.state.gasUsed}${this.props.gasSymbol}`}
            </Text>
          </View>
        </View>
        {/* <View
          style={{
            flexDirection: 'row',
            justifyContent: 'space-between',
            marginBottom: 20,
            height: 30,
            borderRadius: 15,
            backgroundColor: '#571DAA',
            alignItems: 'center',
            justifyContent: 'space-between',
            paddingLeft: 20,
            paddingRight: 20,
          }}>
          <Text style={{color: 'white'}}>Gas Fee</Text>
          <Text
            style={{
              color: 'white',
            }}>{`${this.state.gasUsed}${this.props.gasSymbol}`}</Text>
        </View>
         */}
        <LinerBoardTextInput
          style={{
            width: '100%',
            padding: 0,
            height: 44,
          }}
          defaultValue={this.state.password}
          secureTextEntry={true}
          onChangeText={(text) => {
            this.setState({
              password: text,
            });
          }}
          placeholder="Your wallet password"></LinerBoardTextInput>
        <View
          style={{
            width: '100%',
            flexDirection: 'row',
            justifyContent: 'flex-end',
            marginBottom: 30,
          }}>
          <LinearBoardButton
            buttonStyle={{
              width: 100,
              height: 30,
              marginRight: 20,
            }}
            onPress={() => {
              this.setState({
                modalVisible: false,
              });
            }}
            text={'Cancel'}></LinearBoardButton>
          <LinearButton
            buttonStyle={{
              width: 100,
              height: 30,
            }}
            onPress={this.approve}
            text={'Confirm'}></LinearButton>
        </View>
      </View>
    );
  };

  showTxModal = () => {
    if (this.state.needApprove) {
      this.handleShowWalletConnectSignApprove();
      return;

      this.setState({
        queryingGas: true,
      });

      WalletUtils.getRegisterNFTGasPrice()
        .then((res) => {
          this.setState({
            queryingGas: false,
            gasUsed: res,
            modalVisible: true,
            callFunc: 'approve',
          });
        })
        .catch((err) => {
          console.log('获取失败');
        });
    } else {
      this.handleShowWalletConnectSignBid();
      return;

      this.setState({
        queryingCreateGas: true,
      });

      WalletUtils.getCreateAuctionGasPrice()
        .then((res) => {
          this.setState({
            queryingCreateGas: false,
            gasUsed: res,
            modalVisible: true,
            callFunc: 'Bid',
          });
        })
        .catch((err) => {
          console.log('获取失败');
        });
    }
  };

  approve = () => {
    Keyboard.dismiss();
    this.setState(
      {
        loading: true,
      },
      async () => {
        console.log(this.state.password);

        try {
          var privateKey = await WalletUtils.privateKeyOfKeystore(
            this.props.userInfo.keystore,
            this.state.password,
          );
        } catch (err) {
          console.log('错误' + err);
          this.setState(
            {
              modalVisible: false,
              loading: false,
            },
            () => {
              this._showAlert({content: 'invalid password'});
            },
          );
          return;
        }

        console.log(this.props.signinNFT);

        let {
          payCoinAddress,
          payCoinDecimal,
          nftAddress,
          tokenId,
        } = this.props.navigation.state.params.auction;

        if (this.state.needApprove) {
          WalletUtils.approve(
            privateKey,
            payCoinAddress,
            this.props.proxy.address,
            Number(this.state.amount),
            payCoinDecimal,
            (hash) => {
              this.setState({
                result: '交易已发送，正在监听交易->' + hash,
              });
            },
          )
            .then(async (res) => {
              console.log(res);

              let approveValue = await WalletUtils.queryTokenAllowance(
                this.props.userInfo.metamaskAddress,
                this.props.proxy.address,
                payCoinAddress,
                payCoinDecimal,
              );
              console.log('授权额度为' + approveValue);

              this.setState({
                success: true,
              });

              setTimeout(() => {
                this.setState({
                  approveValue,
                  loading: false,
                  success: false,
                  modalVisible: false,
                  canBid: true,
                  needApprove: false,
                });
              }, 2 * 1000);
            })
            .catch((err) => {
              this.setState(
                {
                  modalVisible: false,
                  loading: false,
                },
                () => {
                  this._showAlert({content: err + ''});
                },
              );
            });
        } else {
          WalletUtils.bid(
            privateKey,
            this.props.proxy.address,
            nftAddress,
            tokenId,
            Number(this.state.amount),
            'signin-app',
            payCoinAddress,
            payCoinDecimal,
            (hash) => {
              this.setState({
                result: '交易已发送，正在监听交易->' + hash,
              });
            },
          )
            .then(async (res) => {
              console.log(res);

              this.setState(
                {
                  loading: false,
                  modalVisible: false,
                },
                () => {
                  this.props.navigation.state.params.refresh();
                  this.props.navigation.goBack();
                },
              );
            })
            .catch((err) => {
              this.setState(
                {
                  modalVisible: false,
                  loading: false,
                },
                () => {
                  this._showAlert({content: 'bid error,please refresh!'});
                },
              );
            });
        }
      },
    );
  };

  formatPrice = (price, payCoinDecimal) => {
    price = new BigNumber(price);
    const decimal = new BigNumber(Math.pow(10, payCoinDecimal));
    let vAmount = parseFloat(price.dividedBy(decimal));
    return ChainUtils.subStringNum(vAmount, 4);
  };

  onPressWalletBackground = () => {
    this.setState({
      showWalletConnect: false,
    });
  };

  resultCall = (hash, err) => {
    if (err) {
      this.setState(
        {
          showWalletConnect: false,
        },
        () => {
          this._showAlert({content: err});
        },
      );
      return;
    }
    console.log('收到交易的HASH回调');
    console.log(hash);

    offerPrice({userToken: this.props.userInfo.token, hash: hash});

    this.setState({
      showWalletConnect: false,
      modalVisible: true,
      loading: true,
    });

    WalletUtils.listenTx(hash)
      .then(async (res) => {
        console.log('交易已上链' + res);

        let {
          payCoinAddress,
          payCoinDecimal,
          nftAddress,
          tokenId,
        } = this.props.navigation.state.params.auction;

        if (this.signinBid) {
          this.setState({
            success: true,
          });
          setTimeout(() => {
            this.setState(
              {
                loading: false,
                modalVisible: false,
              },
              () => {
                this.props.navigation.state.params.refresh();
                this.props.navigation.goBack();
              },
            );
          }, 2 * 1000);
        } else {
          let approveValue = await WalletUtils.queryTokenAllowance(
            this.props.userInfo.metamaskAddress,
            this.props.proxy.address,
            payCoinAddress,
            payCoinDecimal,
          );
          console.log('授权额度为' + approveValue);
          this.setState({
            success: true,
          });
          setTimeout(() => {
            this.setState({
              approveValue,
              loading: false,
              success: false,
              modalVisible: false,
              canBid: true,
              needApprove: false,
            });
          }, 2 * 1000);
        }
      })
      .catch((err) => {
        console.log('交易失败');
        this.setState(
          {
            modalVisible: false,
            loading: false,
          },
          () => {
            this._showAlert({content: err?.message || err + ''});
          },
        );
      });
  };

  handleShowWalletConnectSignApprove = async () => {
    //生成交易
    this._showLoading();
    try {
      this.signinBid = false;

      let {
        payCoinAddress,
        payCoinDecimal,
      } = this.props.navigation.state.params.auction;

      let tx = await WalletUtils.getApproveTx(
        payCoinAddress,
        this.props.proxy.address,
        Number(this.state.amount),
        payCoinDecimal,
        this.props.userInfo.metamaskAddress,
      );

      console.log(tx);
      this._hideLoading();
      //跳转
      this.setState({
        showWalletConnect: true,
        tx,
      });
    } catch (err) {
      this._hideLoading();
      this._showAlert({content: err?.msg || err + ''});
    }
  };

  handleShowWalletConnectSignBid = async () => {
    //生成交易
    this._showLoading();

    this.signinBid = true;

    try {
      let {
        payCoinAddress,
        payCoinDecimal,
        nftAddress,
        tokenId,
      } = this.props.navigation.state.params.auction;

      let tx = await WalletUtils.getBidTx(
        this.props.proxy.address,
        nftAddress,
        tokenId,
        Number(this.state.amount),
        'signin-app',
        payCoinAddress,
        payCoinDecimal,
        this.props.userInfo.metamaskAddress,
      );

      console.log(tx);
      this._hideLoading();
      //跳转
      this.setState({
        showWalletConnect: true,
        tx,
      });
    } catch (err) {
      this._hideLoading();
      this._showAlert({content: err?.msg || err + ''});
    }
  };

  renderComponent = () => {
    let {
      success,
      modalVisible,
      loading,
      approveValue,
      canBid,
      needApprove,
      queryingGas,
      queryingCreateGas,
      showWalletConnect,
      tx,
    } = this.state;

    let {
      startPrice,
      maxPrice,
      bidValue,
      miniIncreasePrice,
      payCoin,
      payCoinDecimal,
      payCoinAddress,
      dealPrice,
      status,
    } = this.props.navigation.state.params.auction;

    startPrice = Number(this.formatPrice(startPrice, payCoinDecimal));
    maxPrice = Number(this.formatPrice(maxPrice, payCoinDecimal));
    bidValue = Number(this.formatPrice(bidValue, payCoinDecimal));
    miniIncreasePrice = Number(
      this.formatPrice(miniIncreasePrice, payCoinDecimal),
    );
    dealPrice = Number(this.formatPrice(dealPrice, payCoinDecimal));

    let tokenModel =
      payCoinAddress !== '0x0000000000000000000000000000000000000000';

    let coin = this.props.coins.filter((item) => {
      return item.symbol == payCoin;
    })[0];

    console.log('==================');
    console.log(coin);

    return (
      <View style={{flex: 1, backgroundColor: '#160231'}}>
        <NormalHeader
          navigation={this.props.navigation}
          text="Place a bid"
          left={{
            icon: require('../../assets/common/common_back_white.png'),
            onPress: () => {
              Keyboard.dismiss();
              this.props.navigation.goBack();
            },
          }}
        />
        <ScrollView
          keyboardDismissMode
          scrollEnabled={false}
          style={{padding: 20, flex: 1}}>
          <View
            style={{
              flexDirection: 'row',
              justifyContent: 'space-between',
              width: '100%',
              // marginBottom: 20,
              padding: 20,
            }}>
            <Text style={{color: '#C917ED', fontWeight: 'bold'}}>Price</Text>
            <Text
              style={{
                fontWeight: 'bold',
                color: 'white',
              }}>{`Balance:${coin.balance} ${payCoin}`}</Text>
          </View>
          <LinerBoardTextInput
            style={{
              width: '100%',
              padding: 0,
              height: 44,
            }}
            keyboardType={'numeric'}
            onChangeText={(text) => {
              let canBid = false;

              if (status == 0) {
                //拍卖中
                canBid =
                  bidValue == 0
                    ? Number(text) >= startPrice
                    : Number(text) >= bidValue + miniIncreasePrice;
              } else if (status == 1) {
                //拍卖结束后的出价
                canBid =
                  bidValue == 0
                    ? Number(text) > dealPrice
                    : Number(text) > dealPrice;
              }

              if (tokenModel) {
                var needApprove = canBid ? approveValue < Number(text) : false;
                canBid = canBid ? approveValue >= Number(text) : false;
              } else {
                canBid = canBid ? Number(text) <= Number(coin.balance) : canBid;
              }

              console.log(approveValue);
              console.log(Number(text));

              this.setState({
                amount: text,
                canBid,
                needApprove,
              });
            }}
            suffix={payCoin}
            placeholder="a higher price than the latest price"></LinerBoardTextInput>
          <View
            style={{
              width: '100%',
              marginTop: 10,
              paddingLeft: 20,
            }}>
            <Text style={{color: 'white', fontSize: 12}}>
              {'Starting price :' +
                (status == 0 ? startPrice : dealPrice) +
                ' ' +
                payCoin}
            </Text>
          </View>
          <View
            style={{
              width: '100%',
              marginTop: 10,
              paddingLeft: 20,
            }}>
            <Text style={{color: 'white', fontSize: 12}}>
              {'Last Price :' + bidValue + ' ' + payCoin}
            </Text>
          </View>
          <View
            style={{
              width: '100%',
              marginTop: 10,
              paddingLeft: 20,
            }}>
            <Text style={{color: 'white', fontSize: 12}}>
              {'Minimun Increase Price :' + miniIncreasePrice + ' ' + payCoin}
            </Text>
          </View>
          <View
            style={{
              width: '100%',
              marginTop: 10,
              paddingLeft: 20,
            }}>
            <Text style={{color: 'white', fontSize: 12}}>
              {'Offer Price :' + maxPrice + ' ' + payCoin}
            </Text>
          </View>
          <View
            style={{
              width: '100%',
              marginTop: 10,
              paddingLeft: 20,
            }}>
            <Text style={{color: 'white', fontSize: 12}}>
              {'Approved allownce of you account for signin:' +
                approveValue +
                ' ' +
                payCoin}
            </Text>
          </View>
          <View
            style={{
              marginTop: 10,
              // height: 30,
              borderRadius: 10,
              backgroundColor: '#571DAA',
              alignItems: 'center',
              justifyContent: 'center',
              padding: 10,
            }}>
            <Text style={{color: 'white'}}>
              {status
                ? 'If there is a higher bid, your bid will be returned to your account. If the user does not agree to your bid within 7 days, your bid will also be returned.'
                : 'If there is a higher bid, your bid will be returned to your account. At the end of the auction, the user with the highest bid will receive this NFT'}
            </Text>
          </View>
          <View
            style={{
              flexDirection: 'row',
              justifyContent: 'center',
              alignItems: 'center',
              marginBottom: 70,
            }}>
            {tokenModel ? (
              <LinearButton
                buttonStyle={{
                  width: '40%',
                  marginRight: 10,
                }}
                loading={queryingGas}
                isDisabled={!needApprove}
                text={canBid ? 'Approved' : 'Approve'}
                onPress={this.showTxModal}
              />
            ) : null}
            {tokenModel ? (
              <Image
                style={{
                  width: 30,
                  height: 30,
                  marginRight: 10,
                  marginTop: 20,
                  alignSelf: 'center',
                }}
                source={require('../../assets/auction/next_step.png')}
              />
            ) : null}
            <LinearButton
              isDisabled={!canBid}
              loading={queryingCreateGas}
              buttonStyle={{width: '40%'}}
              text={'Bid'}
              onPress={this.showTxModal}
            />
          </View>
          <View
            style={{
              width: '100%',
              height: this.props.widgetLayout.show
                ? this.props.widgetLayout.height
                : 0,
              marginTop: 10,
            }}></View>
        </ScrollView>

        {/* <View
          style={{
            width: '100%',
            flexDirection: 'row',
            justifyContent: 'center',
            marginBottom: 70,
          }}>
          <LinearBoardButton
            text={'Approve'}
            buttonStyle={{
              width: 150,
              marginRight: 20,
            }}
            onPress={() => {
              this.props.navigation.navigate('ConvertHT');
            }}></LinearBoardButton>
          {valid ? (
            <LinearButton
              buttonStyle={{
                width: 150,
              }}
              onPress={this.showTxModal}
              text={'Confirm'}
            />
          ) : (
            <TextButton
              buttonStyle={{
                width: 150,
                borderRadius: 22,
                backgroundColor: '#B6B6B6',
              }}
              isDisabled={!valid}
              onPress={this.showTxModal}
              text={'Confirm'}></TextButton>
          )}
        </View> */}
        <ModalHandler
          visible={modalVisible}
          loading={loading}
          success={success}
          handlerView={this._handlerView}
          onPressBackground={this.onPressBackground}
        />
        <WalletConnectModal
          visible={showWalletConnect}
          resultCall={this.resultCall}
          onPressBackground={this.onPressWalletBackground}
          tx={tx}></WalletConnectModal>
      </View>
    );
  };
}

const mapStateToProps = (state) => ({
  userInfo: state.User.userInfo,
  coins: state.Chain.coins,
  proxy: state.Chain.proxy,
  gasSymbol: state.Chain.gasSymbol,
  widgetLayout: state.Layout.widgetLayout,
});

const mapDispatchToProps = (dispatch) => ({
  queryWalltBalance: () => dispatch(queryWalltBalance()),
});
export default connect(mapStateToProps, mapDispatchToProps)(PriceBid);
